import 'package:flutter/material.dart';
import 'package:bear_story/views.dart';
import '../bean/beans.dart';
import '../main.dart';

class PlayerPage extends StatefulWidget {
//  final List<Chapter> chapters;
//  final int index;
//
//  PlayerPage(this.chapters, this.index)
//      :assert(chapters != null),
//        assert(index >= 0),
//        assert(index < chapters.length);

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _PlayerPageState();
  }
}

class _PlayerPageState extends State<PlayerPage>
    with SingleTickerProviderStateMixin, EventChannelListener, PlayChaptersUpdateListener {
  double _sliderValue = 0.0;
  double _sliderMax = 1000;

  AnimationController controller; //动画控制器
  CurvedAnimation curved; //曲线动画，动画插值，

  _PlayerPageState() {
    controller = new AnimationController(duration: const Duration(seconds: 14), vsync: this);
    curved = new CurvedAnimation(parent: controller, curve: Curves.linear);
    controller.addStatusListener((AnimationStatus status) {
//      print("status == $status");
    });
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    print("player-----initState");
    addPlayChaptersUpdateListener(this);
    addEventChannelListener(this);
  }

  @override
  void dispose() {
    controller.stop();
    super.dispose();
    print("player-----dispose");
    removePlayChaptersUpdateListener(this);
    removeEventChannelListener(this);
  }

  Widget getAlbumListView(BuildContext context) {
    return Container(
      constraints: BoxConstraints.expand(height: 360),
      decoration:
          BoxDecoration(borderRadius: BorderRadius.only(topLeft: Radius.circular(6), topRight: Radius.circular(6))),
      child: ListView(
        children: getListItems(),
      ),
    );
  }

  List<Widget> getListItems() {
    List<Chapter> chapters = getNowPlayChapters();
    List<Widget> list = [];
    for (int index = 0; index < chapters.length; index++) {
      final int nowIndex = getNowPlayIndex();
      final Chapter _chapter = chapters[index];
      final bool isPlaying = nowIndex == index;
      Widget w = GestureDetector(
        onTap: () {
          print("player--onTap+++");
          if (!isPlaying) {
            playList(getNowPlayChapters(), index, getNowPlayBook(), true);
          }
          Navigator.of(context).pop();
        },
        child: Container(
          constraints: BoxConstraints.expand(height: 71),
          color: Colors.white,
          child: Column(
            children: <Widget>[
              Expanded(
                  child: Container(
                padding: EdgeInsets.only(left: 24, right: 24, top: 10),
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: <Widget>[
                    Text(
                      (index + 1).toString(),
                      maxLines: 1,
                      style: TextStyle(color: Color(0xff666666), fontSize: 16, fontWeight: FontWeight.w400),
                    ),
                    Padding(
                      padding: EdgeInsets.only(left: 24),
                    ),
                    Expanded(
                        child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Text(
                          _chapter.name,
                          maxLines: 1,
                          style: TextStyle(
                              color: isPlaying ? main_theme_color : Color(0xff333333),
                              fontSize: 17,
                              fontWeight: FontWeight.w500),
                        ),
                        Padding(padding: EdgeInsets.only(top: 8)),
                        Row(
                          children: <Widget>[
                            Icon(
                              Icons.access_time,
                              color: Color(0xFFcdcdcd),
                              size: 12,
                            ),
                            Padding(
                              padding: EdgeInsets.only(left: 2),
                            ),
                            Text(
                              _chapter == null ? "" : _chapter.getTimeStr(1),
                              style: TextStyle(fontSize: 11, color: Color(0xff999999), fontWeight: FontWeight.w400),
                            )
                          ],
                        ),
                      ],
                    )),
                    Offstage(
                      offstage: !isPlaying,
                      child: Image.asset(
                        "images/play_state2.gif",
                        width: 20,
                        height: 23,
                        fit: BoxFit.fill,
                      ),
                    ),
                  ],
                ),
              )),
              Padding(
                padding: EdgeInsets.symmetric(horizontal: 24),
                child: Divider(
                  color: Color(0xffe3e3e3),
                ),
              ),
            ],
          ),
        ),
      );

      list.add(w);
    }
    return list;
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    Chapter chapter = getNowPlayChapter();
    if (isPlaying()) {
      controller.repeat();
    } else {
      controller.stop();
    }
    Book nowBook = getNowPlayBook();
    return Scaffold(
      appBar: null,
      body: Stack(
        children: <Widget>[
          ConstrainedBox(
            constraints: BoxConstraints.expand(),
            child: Image.asset(
              "images/play_bg.png",
              fit: BoxFit.cover,
            ),
          ),
          Padding(
            padding: EdgeInsets.only(top: status_bar_height + 5),
            child: IconButton(
                icon: Icon(Icons.arrow_back_ios),
                iconSize: 27,
                color: Colors.white,
                onPressed: () {
                  Navigator.of(context).pop();
                }),
          ),
          Padding(
            padding: EdgeInsets.only(left: 15, right: 15, top: status_bar_height + 27 + 40, bottom: 28),
            child: ConstrainedBox(
              constraints: BoxConstraints.expand(),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  ClipOval(
                    child: Container(
                      width: 220,
                      height: 220,
                      color: Color(0x25ffffff),
                      child: Center(
                        child: RotationTransition(
                          turns: curved,
                          child: ClipOval(
                            child: Container(
                              width: 210,
                              height: 210,
                              child: Image.network(
                                chapter.pic,
                                fit: BoxFit.cover,
                              ),
                            ),
                          ),
                        ),
                      ),
                    ),
                  ),
                  Padding(padding: EdgeInsets.only(top: 40)),
                  Expanded(
                    child: SingleChildScrollView(
                      child: Column(
                        children: <Widget>[
                          Text(
                            chapter.name,
                            style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold, color: Colors.white),
                          ),
                          Padding(
                            padding: EdgeInsets.only(top: 10),
                          ),
                          Text(
                            nowBook == null ? "" : "《${nowBook.bookname}》",
                            style: TextStyle(fontSize: 17, color: Colors.white),
                          )
                        ],
                      ),
                    ),
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      Text(
                        chapter.getTimeStr(getPlayerProgress()),
                        style: TextStyle(
                          fontSize: 12,
                          color: Colors.white,
                        ),
                      ),
                      Expanded(
                          child: Container(
                        padding: const EdgeInsets.only(left: 3, right: 3),
                        child: SliderTheme(
                            data: SliderThemeData(
                              trackHeight: 5,
                              inactiveTrackColor: Colors.white,
                              activeTrackColor: main_theme_color,
                              thumbColor: main_theme_color,
                              trackShape: MySliderTrackShape(),
                              //气泡显示的形式
                              showValueIndicator: ShowValueIndicator.never,
                              thumbShape: RoundSliderThumbShape(enabledThumbRadius: 9),
                              //按下thumb没有overlay效果
                              overlayShape: SliderComponentShape.noOverlay,
                            ),
                            child: Slider(
                                min: 0,
                                max: _sliderMax,
                                value: _sliderValue,
                                onChangeEnd: (value) {
                                  channelSeekToByPercent(value / _sliderMax, chapter.chaptertime);
                                },
                                onChanged: (double value) {
                                  setState(() {
                                    _sliderValue = value;
                                  });
                                })),
                      )),
                      Text(
                        chapter.getTimeStr(1),
                        style: TextStyle(
                          fontSize: 12,
                          color: Colors.white,
                        ),
                      ),
                    ],
                  ),
                  Padding(padding: EdgeInsets.only(top: 14)),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      GestureDetector(
                        onTap: () {
                          if (nowPlayModel == 0) {
                            channelSetPlayModel(1).then((v) {
                              if (v) {
                                showToast("当前模式：单曲循环", context);
                                setState(() {});
                              }
                            });
                          } else {
                            channelSetPlayModel(0).then((v) {
                              if (v) {
                                showToast("当前模式：列表循环", context);
                                setState(() {});
                              }
                            });
                          }
                        },
                        child: Image.asset(
                          nowPlayModel == 0 ? "images/play_xh.png" : "images/play_xh1.png",
                          width: 21,
                          height: 21,
                          fit: BoxFit.fill,
                        ),
                      ),
                      GestureDetector(
                        onTap: () {
                          channelPlayerPrev();
                        },
                        child: Image.asset(
                          "images/play_last.png",
                          width: 21,
                          height: 21,
                          fit: BoxFit.fill,
                        ),
                      ),
                      GestureDetector(
                        onTap: () {
                          if (isPlaying()) {
                            channelPlayerPause();
                          } else {
                            channelPlayerPlay();
                          }
                        },
                        child: Image.asset(
                          isPlaying() ? "images/play_pause.png" : "images/play_play.png",
                          width: 62,
                          height: 62,
                          fit: BoxFit.fill,
                        ),
                      ),
                      GestureDetector(
                        onTap: () {
                          channelPlayerNext();
                        },
                        child: Image.asset(
                          "images/play_next.png",
                          width: 21,
                          height: 21,
                          fit: BoxFit.fill,
                        ),
                      ),
                      GestureDetector(
                        onTap: () {
                          showModalBottomSheet(
                              context: context,
                              builder: (BuildContext context) {
                                return getAlbumListView(context);
                              });
                        },
                        child: Image.asset(
                          "images/play_album.png",
                          width: 21,
                          height: 21,
                          fit: BoxFit.fill,
                        ),
                      ),
                    ],
                  )
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  @override
  void onPlayChaptersUpdate() {
    // TODO: implement onPlayChaptersUpdate
    setState(() {});
  }

  @override
  void onEvent(Map map) {
    // TODO: implement onEvent
    String type = map["type"];
//    print("player-----onEvent");
    if (type == "player") {
      setState(() {
        String status = map["status"];
        if (status == "onPlayProgress" || status == "onPlayProgress_ios") {
          _sliderValue = getPlayerProgress() * _sliderMax;
        }
      });
    }
  }
}
